# -*- coding: utf-8 -*-
import os,time
import wordcloud, jieba
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import write,grabcut

def run(av,file,img):
    # 输出文件夹
    output = 'static/wordcloud/'

    text = write.text(file)
    os.remove(file)

    if text == '':
        print('生成词云失败: av'+av+'没有任何弹幕')
        return 'no word'

    # 使用结巴分词
    # text = text + ' '.join(jieba.cut(text))
    print(text[:100])
   
    # 计算形状
    img_mask = grabcut.run(img)

    # 设置形状
    mask = np.array(Image.open(img_mask))
    os.remove(img_mask)
    w = wordcloud.WordCloud(mask=mask,font_path='font/loli.ttf', background_color='#fff')
    try:
        w.generate(text)
    except:
        print('生成词云失败: av'+av+'封面图片过小')
        return 'too small'
    # 保存文件
    filename = 'wordcloud' + av +'.png'
    path = os.path.join(output,filename)
    w.to_file(path)

    # # 显示图片
    # plt.imshow(w, interpolation='bilinear')
    # plt.axis('off')
    # plt.show()
    return path + '?id=' + str(time.time())
